import json
from collections import defaultdict

from anthropic import BaseModel
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from database.config import get_db
from lagent.agents import ability_suggestion
from lagent.agents.ability_suggestion import AbilitySuggestion
from lagent.agents.position_recommand import PositionRecommand
from models.model import *
from models.base import *
from utils.deps import verify_token

router = APIRouter()

# 岗位选择
class PositionChoice(BaseModel):
    position: str
@router.post("/position_choice")
async def position_choice(positionChoice: PositionChoice,
                          currentUser: dict = Depends(verify_token),  # 添加 token 验证
                          db: Session = Depends(get_db)):
    username = currentUser['username']
    position = positionChoice.position

    user = db.query(User).filter(User.username == username).first()
    user.position = position
    db.commit()

    return Success(code = 200, msg = "success", res_data = {})

# 岗位推荐
@router.get("/recommend_position")
async def recommend_position( currentUser: dict = Depends(verify_token),  # 添加 token 验证
                          db: Session = Depends(get_db)):
    username = currentUser['username']
    userResume = db.query(Resume).filter(Resume.username == username).first()
    user = db.query(User).filter(User.username == username).first()

    resume = userResume.resume_content # 简历内容

    # 推荐岗位
    positionRecommand = PositionRecommand(resume=resume)
    positionByAI = positionRecommand.recommand_position()
    user.position_by_ai = positionByAI
    db.commit()

    res_data = {"position_name": positionByAI}
    return Success(code = 200, msg = "success", res_data = res_data)

# 获取面试结果
@router.get("/result")
async def interview_result(currentUser: dict = Depends(verify_token),
                           db: Session = Depends(get_db)):
    username = currentUser['username']
    user = db.query(User).filter(User.username == username).first()
    recordList = db.query(InterviewRecord).filter(InterviewRecord.username == username).all()
    recordLength = len(recordList)

    # 需要计算的字段
    fields = ['professional_knowledge', 'adaptability', 'skill_match','innovation', 'communication', 'logical_thinking']

    # 雷达图数据
    current_evaluate = {} # 本次数据
    prev_evaluate = defaultdict(int) # 上次数据
    avg_evaluate = defaultdict(int) # 平均数据
    # 计算平均数据
    for record in recordList:
        for field in fields:
            avg_evaluate[field] += getattr(record, field)
    for field in fields:
        avg_evaluate[field] /= recordLength
    # 计算本次数据
    last_record = recordList[-1]
    for field in fields:
        current_evaluate[field] = getattr(last_record, field)
    # 计算上次数据
    if recordLength > 1:
        second_last_record = recordList[-2]
        for field in fields:
            prev_evaluate[field] = getattr(second_last_record, field)
    radar_chart = {
        'current_evaluate': current_evaluate,
        'avg_evaluate': avg_evaluate,
        'prev_evaluate': prev_evaluate,
    }

    # 面试综述
    overview_score = 0
    for field in fields:
        overview_score += avg_evaluate[field]
    overview_score = overview_score / len(avg_evaluate)
    overview_score = round(overview_score, 2)  # 保留两位小数
    performance = last_record.evaluation
    ability_assessment = ""
    interview_overview = {
        'performance': performance,
        'ability_assessment': ability_assessment,
        'score': overview_score
    }

    # 能力细节
    ability_details = {
        'professional_knowledge': {},
        'adaptability': {},
        'skill_match': {},
        'innovation': {},
        'communication': {},
        'logical_thinking': {}
    }
    ability_map = {
        'professional_knowledge': '专业知识水平',
        'adaptability': '应变抗压能力',
        'skill_match': '技能匹配度',
        'innovation': '创新能力',
        'communication': '语言表达能力',
        'logical_thinking': '逻辑思维能力'
    }
    ability_evalaute_str = ''

    # 单个维度能力评价
    for field in fields:
        ability_details[field]["evaluate"] = getattr(last_record, f"{field}_evaluate")
        ability_evalaute_str += f"在{ability_map[field]}方面的评价是{ability_details[field]['evaluate']}\n"
    # 调用llm获得评价
    abilitySuggestion = AbilitySuggestion(position = user.position, ability_evalaute = ability_evalaute_str)
    ability_advice = abilitySuggestion.get_ability_suggestion()
    print(ability_advice)
    print(type(ability_advice))

    # 单个维度能力建议
    for field in fields:
        column = f"{field}_advice"
        ability_details[field]["suggestion"] = ability_advice[column]
        setattr(recordList[-1], column, ability_details[field]["suggestion"])

    db.commit()

    res_data = {
        'radar_chart': radar_chart,
        'interview_overview': interview_overview,
        'ability_details': ability_details,
    }
    return Success(code = 200, msg = "success", res_data = res_data)
